import requests
import json
from dataclasses import dataclass

@dataclass
class ReturnStatus :
    messageType: str
    _server_information_: str
    data: str
    message: str
    status: str


user = {
    "username": "cuiml10",
}

config = {
    "servname": "LIMS-Server",
    "mituser": "cuiml10",
    "funcname": "getTestForm",
    "username": "cuiml10",
}

local = {
    "scheme": "http",
    "domain": "limslocal.midea.com",
}

dev = {
    "scheme": "https",
    "domain": "limsdev.midea.com",
}

sit = {
    "scheme": "https",
    "domain": "limssit.midea.com",
}

uat = {
    "scheme": "https",
    "domain": "limsuat.midea.com",
}

ver = {
    "scheme": "https",
    "domain": "limsver.midea.com",
}

prod = {
    "scheme": "https",
    "domain": "lims.midea.com",
}

headers = {
    "Content-Type": "application/json",  # 设置请求头为JSON格式
    "__TokenAuthorization_UserName_": config['username'],
    "__TokenAuthorization_Function_": config["funcname"],
    "__TokenAuthorization_UID_": "<KEY>"
}


def getToken(env="local"):
    """
    获取 LIMS 系统的 Token
    :return: 成功返回 token 字符串，失败返回 None
    """
    try:
        url = realTokenUrl(env)
        response = requests.post(url, headers=headers)
        response.raise_for_status()  # 检查HTTP错误
        data = json.loads(response.text)
        return data.get("token")  # 返回token字段值
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")
    except json.JSONDecodeError:
        print("响应不是有效的JSON格式")
    except KeyError:
        print("JSON中未找到'token'字段")
    return None  # 失败时返回None

def getUrls(url):
    urls = [f"{evn['scheme']}://{evn['domain']}/{config['servname']}/{url}" for evn in [local, dev, sit, uat, ver, prod]]
    return urls

def getTokenUrls():
    tokenurls = [f"{env['scheme']}://{env['domain']}/{config['servname']}/MPLM_Service_Gateway/TokenGenerator/getToken"
                 for env in [local, dev, sit, uat, ver, prod]]
    return tokenurls

def realTokenUrl(env='uat'):
    urls = getTokenUrls()
    if env == 'local':
        return urls[0]
    elif env == 'dev':
        return urls[1]
    elif env == 'sit':
        return urls[2]
    elif env == 'uat':
        return urls[3]
    elif env == 'ver':
        return urls[4]
    elif env == 'prod':
        return urls[5]
    else:
        return urls[3]

def realUrl(url, env='uat'):
    urls = getUrls(url)
    if env == 'local':
        return urls[0]
    elif env == 'dev':
        return urls[1]
    elif env == 'sit':
        return urls[2]
    elif env == 'uat':
        return urls[3]
    elif env == 'ver':
        return urls[4]
    elif env == 'prod':
        return urls[5]
    else:
        return urls[3]


def get(url,env='uat',params=None, headers=headers):
    """
        发送 GET 请求
        :param url: 请求的URL
        :param params: 请求参数
        :param headers: 请求头
        :return: 返回请求结果
    """
    try:
        token = getToken(env)
        headers['__TokenAuthorization_UID_'] = token
        url = realUrl(url, env)
        response = requests.get(url, headers=headers, params=params)
        response.raise_for_status()  # 检查HTTP错误
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")


def post(url, env='uat', params=None, headers=headers):
    """
        发送 POST 请求
        :param url: 请求的URL
        :param params: 请求体参数
        :param headers: 请求头
        :return: 返回请求结果
    """
    try:
        token = getToken(env)
        headers['__TokenAuthorization_UID_'] = token
        url = realUrl(url, env)
        response = requests.post(url, headers=headers, data=json.dumps(params))
        response.raise_for_status()  # 检查HTTP错误
        return response.text
    except requests.exceptions.RequestException as e:
        print(f"请求失败: {e}")




